<?php

namespace App\Console\Commands\OpenShop;

use App\Service\OpenShop\Statistical\SignOrderStatisticalService;
use Guanguans\Notify\Factory;
use Guanguans\Notify\Messages\FeiShu\CardMessage;
use Illuminate\Console\Command;

class InvestmentScheduleNotice extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'open_shop:investment_schedule_notice {env=prod}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '招商进度提醒';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     * @throws \Exception
     */
    public function handle()
    {

        $date         = date('Y-m-01');     // 本月1号
        $totalDay     = date('t');          // 当月总天数
        $nowDay       = date('d');          // 当天数
        $remainingDay = ($totalDay - $nowDay) + 1;// 当月剩余天数
        $remainingDay = $remainingDay >= 0 ? $remainingDay : 0;
        if ($nowDay < 16 && self::isProd()) {// 9.30推送，每月16号开始至月底
            return 0;
        }
        $data = SignOrderStatisticalService::getMonthSigningCompletionData($date);

        if (!($data['monthCompleteData'] && $data['rankData'])) {
            return 0;
        }

        $card = [
            "config"   => [
                "wide_screen_mode" => true
            ],
            "elements" => [
                [
                    "tag"  => "div",
                    "text" => [
                        "content" => "🔥 本月签约进度（倒计时：{$remainingDay} 天）",
                        "tag"     => "lark_md"
                    ]
                ],
            ],
            "header"   => [
                "template" => "red",
                "title"    => [
                    "content" => "🔥🔥🔥 本月签约进度🔥🔥🔥 ",
                    "tag"     => "plain_text"
                ]
            ]
        ];

        if ($data['monthCompleteData']) {
            $remainingShopCount = $data['monthCompleteData']['targetShopCount'] - $data['monthCompleteData']['newShopCount'];
            $remainingStr       = "剩余签约\n<font color='green'>  {$remainingShopCount}</font>";
            if ($remainingShopCount < 0) {
                $remainingShopCount = abs($remainingShopCount);
                $remainingStr       = "超额签约\n<font color='red'>  {$remainingShopCount}</font>";
            }
            $card['elements'] = array_merge(
                $card['elements'], [
                    [
                        "tag"              => "column_set",
                        "flex_mode"        => "none",
                        "background_style" => "default",
                        "columns"          => [
                            /*[
                                "tag"            => "column",
                                "width"          => "weighted",
                                "weight"         => 1,
                                "vertical_align" => "top",
                                "elements"       => [
                                    [
                                        "tag"              => "column_set",
                                        "flex_mode"        => "none",
                                        "background_style" => "grey",
                                        "columns"          => [
                                            [
                                                "tag"            => "column",
                                                "width"          => "weighted",
                                                "weight"         => 1,
                                                "vertical_align" => "top",
                                                "elements"       => [
                                                    [
                                                        "tag"        => "markdown",
                                                        "content"    => "**签约目标\n<font color='green'> {$data['monthCompleteData']['targetShopCount']}</font>**",
                                                        "text_align" => "center"
                                                    ]
                                                ]
                                            ]
                                        ]
                                    ]
                                ]
                            ],*/
                            [
                                "tag"            => "column",
                                "width"          => "weighted",
                                "weight"         => 1,
                                "vertical_align" => "top",
                                "elements"       => [
                                    [
                                        "tag"              => "column_set",
                                        "flex_mode"        => "none",
                                        "background_style" => "grey",
                                        "columns"          => [
                                            [
                                                "tag"            => "column",
                                                "width"          => "weighted",
                                                "weight"         => 1,
                                                "vertical_align" => "top",
                                                "elements"       => [
                                                    [
                                                        "tag"        => "markdown",
                                                        "content"    => "**已签约\n<font color='green'>  {$data['monthCompleteData']['newShopCount']}</font>**",
                                                        "text_align" => "center"
                                                    ]
                                                ]
                                            ]
                                        ]
                                    ]
                                ]
                            ],
                            /*[
                                "tag"            => "column",
                                "width"          => "weighted",
                                "weight"         => 1,
                                "vertical_align" => "top",
                                "elements"       => [
                                    [
                                        "tag"              => "column_set",
                                        "flex_mode"        => "none",
                                        "background_style" => "grey",
                                        "columns"          => [
                                            [
                                                "tag"            => "column",
                                                "width"          => "weighted",
                                                "weight"         => 1,
                                                "vertical_align" => "top",
                                                "elements"       => [
                                                    [
                                                        "tag"        => "markdown",
                                                        "content"    => "**{$remainingStr}**",
                                                        "text_align" => "center"
                                                    ]
                                                ]
                                            ]
                                        ]
                                    ]
                                ]
                            ]*/
                        ]
                    ]
                ]

            );

        }

        if ($data['rankData']) {

            // 根据总金额排序
            array_multisort(array_column($data['rankData'], 'complete'), SORT_DESC, $data['rankData']);
            $rankStr = '';
            foreach ($data['rankData'] as $k => $v) {
                if (!$v['name']) {
                    continue;
                }
                if ($v['remain'] < 0) {
                    $v['remain'] = abs($v['remain']);
                    $remainStr   = "<font color='red'> 超额 </font>";
                } else {
                    $remainStr = "<font color='green'> 剩余 </font>";
                }
                $remainStr .= $v['remain'] / 10000;
                $userName  = self::getUserOpenIdTag($v['name']);
                $rankStr   .= ($k + 1) . ". {$userName} 已回款" . ($v['complete'] / 10000) . "万，" . $remainStr . " 万完成当月业绩。\n";
            }
            $card['elements'] = array_merge(
                $card['elements'],
                [
                    [
                        "tag" => "hr"
                    ],
                    [
                        "tag"  => "div",
                        "text" => [
                            "content" => "🔥  本月业绩排名",
                            "tag"     => "plain_text"
                        ]
                    ],
                    [
                        "tag"  => "div",
                        "text" => [
                            "content" => "$rankStr",
                            "tag"     => "lark_md"
                        ]
                    ],
                    [
                        "tag"      => "note",
                        "elements" => [
                            [
                                "tag"     => "plain_text",
                                "content" => "💡 [机密] 请注意信息安全，严禁外传"
                            ]
                        ]
                    ]
                ]
            );
        }

        $robot = self::getRobot();
        Factory::feiShu()
            ->setToken($robot['urlToken'])
            ->setSecret($robot['secret'])
            ->setMessage(new CardMessage($card))
            ->send();
    }


    private function getRobot(): array
    {
        if (self::isProd()) {

            // 商家增长中心群 群
            return [
                'url'      => 'https://open.feishu.cn/open-apis/bot/v2/hook/f143cc41-1dd9-487c-9d98-d0325bc60e9f',
                'urlToken' => 'f143cc41-1dd9-487c-9d98-d0325bc60e9f',
                'secret'   => 'KqtvpLBuw7FIhQT74XFBdd'
            ];
        } else {

            // 商增机器人开发 群
            return [
                'url'      => 'https://open.feishu.cn/open-apis/bot/v2/hook/6bebe69e-9d92-420e-a292-741149935599',
                'urlToken' => '6bebe69e-9d92-420e-a292-741149935599',
                'secret'   => 'GUo19hJXdqZWag1GKLd9Ab'
            ];
        }
    }

    private function isProd(): bool
    {
        if ('prod' == $this->argument('env') && config('app.env') == 'prod') {
            return true;
        } else {
            return false;
        }
    }


    private function getUserOpenIdTag($userName): string
    {
        return "<font color='green'> $userName </font>";
//        return "<at id>$userName</at>";
    }
}
